package com.xsy.de.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.xsy.de.entity.User;
import com.xsy.de.service.UserService;
import com.xsy.de.util.EhcacheUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author DingHao
 * @since 2019-06-07
 */
@Controller
@RequestMapping("/user")
public class UserController extends ApiController {
    private final static Logger log = LogManager.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    /**
     * 查找所人员
     * @return
     */
    @GetMapping("/userList")
    @ResponseBody
    public List<User> getAllStudent(){
        return userService.selectList(null);
    }

    /**
     * 添加人员
     * @param
     * @return
     */
    @PostMapping(value = "/userReg")
    @ResponseBody
    public String addUser(String username,String code, String userpwd, HttpServletRequest request, HttpServletResponse response){
        log.debug("注册手机号："+username+";密码："+userpwd+";验证码："+code);
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(userpwd) && StringUtils.isNotBlank(code)) {
            String cacheCode = EhcacheUtil.get( "SMS", username +"Code").toString();
            if (StringUtils.isBlank(cacheCode) || !code.equals(cacheCode)){
                return "3";//验证码为空或者输入错误
            }
            //查询注册用户是否已存在
            QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
            queryWrapper.eq("USER_NAME", request.getParameter("username"));
            List<User> users = userService.selectList(queryWrapper);
            if (users.size() > 0){
                return "4";//用户已存在
            }
            User user = new User();
            user.setUserName(username);
            user.setUserPwd(userpwd);
            user.setStatus("1");
            user.setCreateDate(LocalDateTime.now());
            boolean result = userService.insert(user);
            if (result){
                return "0";
            }else {
                return "1";
            }
        }
        return "2";
    }

}

